package com.yuantu.judiciary.dao;

import com.yuantu.judiciary.model.domain.InviteRecordDO;
import com.yuantu.judiciary.model.enums.InviteCodeType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * 邀请码
 *
 * @author syw
 * @since 2023-08-17
 **/
public interface IInviteRecordDao extends JpaRepository<InviteRecordDO, Long> {

    /**
     * 推荐码组织内不可重复
     */
    InviteRecordDO findRecordByInviteCodeAndOrganizationIdAndDeletedFalse(String inviteCode, Long organizationId);

    /**
     * 邀请码组织内可重复
     */
    InviteRecordDO findRecordByInviteCodeAndCreatorIdAndDeletedFalse(String inviteCode, Long creatorId);

    List<InviteRecordDO> findRecordByInviteCodeAndDeletedFalse(String inviteCode);

    List<InviteRecordDO> findRecordByCreatorIdAndTypeAndDeletedFalse(Long creatorId, InviteCodeType type);

    List<InviteRecordDO> findRecordByInviteCodeInAndDeletedFalse(List<String> inviteCode);

    @Modifying
    @Query("update InviteRecordDO ir set ir.inviteCode = ?2 where ir.inviteCode = ?1")
    void updateInviteCode(String existInviteCode, String newInviteCode);


    @Query(nativeQuery = true, value = "select ir.invite_code from invite_record ir left join invite_code ic on ir.invite_code = ic.invite_code " +
            "left join account a on a.id = ic.operator_id  " +
            "where ir.is_deleted = 0 and ic.is_deleted = 0 and a.is_deleted = 0 " +
            "group by invite_code order by count(ir.id) desc limit 100 ")
    List<String> findTOP100InviteCode();

    List<InviteRecordDO> findRecordByInviteCodeAndTypeAndDeletedFalse(String inviteCode, InviteCodeType type);

}
